package cn.wh.org.service.impl;

import cn.wh.basic.service.impl.BaseServiceImpl;
import cn.wh.org.domain.Department;
import cn.wh.org.mapper.DepartmentMapper;
import cn.wh.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {

        departmentMapper.save(department);
        this.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //定义一个字符串,用于接收拼接好的dirPath
            String dirPath = "";
            //判断是否是顶级数据
            if(department.getDepartment() == null){
               //如果是顶级,那么dirPath就是本身自己
               dirPath = "/"+department.getId();
            }else{
                //如果不是顶级,那么先获取当前数据的上级部门dirPath
                Department dept = departmentMapper.loadById(department.getDepartment().getId());
                //根据上级部门的dirPath+当前数据id,拼接成dirPath
                dirPath = dept.getDirPath() + "/" +department.getId();
            }
            department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    public List<Department> queryTree(){
        //找到所有department的数据
        List<Department> departments = departmentMapper.loadAll();
        //为了后面找到自己的父亲,我们这里可以把整体的部门数据转换一份成Map
        Map<Long,Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            allDepts.put(department.getId(), department);
        }
        List<Department> firstDepts = new ArrayList<>();
        for (Department tmp : departments) {
            if (tmp.getParent_id() == null){
                firstDepts.add(tmp);
            }else{
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }

}
